package com.sync.hkmjsyncdata.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkPerson;
import com.sync.hkmjsyncdata.pojo.po.HkPoint;
import com.sync.hkmjsyncdata.service.IHkPersonService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncMjPerson {

    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;

    @Resource
    IHkPersonService personService;


    /**
     * 同步海康人员
     */
    @XxlJob("SyncMjPerson")
    public void SyncMjPersonData() {
        XxlJobHelper.log("开始同步海康门禁人员信息");
        List<HkPerson> allResult = personService.list();
        if (ObjectUtils.isNotEmpty(allResult)) {
            XxlJobHelper.log("数据库已有海康人员信息：{}条", allResult.size());
//            LambdaQueryWrapper<HkPerson> queryWrapper=new LambdaQueryWrapper<>();
//            queryWrapper.eq(HkPerson::getOpTyp,4).last(" limit 1");
//            List<HkPerson> result=personService.list(queryWrapper);
//            if(ObjectUtils.isEmpty(result)){
//                XxlJobHelper.log("数据库已有海康人员信息未推送工业互联网,停止拉取");
//                return;
//            }
        }
        JSONObject orgParams = new JSONObject();
        orgParams.put(PAGE_NO_KEY, 1);
        orgParams.put(PAGE_SIZE_KEY, 1000);
        String resultInfo = centerUtilsService.doPost("/api/resource/v1/org/orgList", orgParams.toJSONString());
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject orgResult = JSON.parseObject(resultInfo);
            JSONObject orgData = orgResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(orgData) && ObjectUtils.isNotEmpty(orgData.getJSONArray("list"))) {
                JSONArray list = orgData.getJSONArray("list");
                Map<String, String> orgMap = new HashMap<>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject personInfo = list.getJSONObject(i);
                    orgMap.put(personInfo.getString("orgIndexCode"), personInfo.getString("orgPath"));
                }
                List<HkPerson> newPersons = new ArrayList<>();
                SyncMjPersonDataByHk(1, newPersons, orgMap);
                bulidMjPersonInfo(allResult, newPersons);
            } else {
                XxlJobHelper.log("同步海康门禁组织信息失败");
            }
        }

    }


    private void SyncMjPersonDataByHk(int pageNo, List<HkPerson> newPersons, Map<String, String> orgMap) {

        JSONObject personParams = new JSONObject();
        personParams.put(PAGE_NO_KEY, pageNo);
        personParams.put(PAGE_SIZE_KEY, 1000);
        XxlJobHelper.log("同步海康门禁人员信息查询条件：{}", personParams.toJSONString());
        String resultInfo = centerUtilsService.doPost("/api/resource/v2/person/personList", personParams.toJSONString());
        XxlJobHelper.log("同步海康门禁人员信息返回：{}", resultInfo);
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject personResult = JSON.parseObject(resultInfo);
            JSONObject personData = personResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(personData) && ObjectUtils.isNotEmpty(personData.getJSONArray("list"))) {
                JSONArray list = personData.getJSONArray("list");
                for (int i = 0; i < list.size(); i++) {
                    JSONObject personInfo = list.getJSONObject(i);
                    newPersons.add(new HkPerson()
                            .setUsrIdCard(personInfo.getString("certificateNo"))
                            .setPhone(personInfo.getString("phoneNo"))
                            .setUsrCod(personInfo.getString("jobNo"))
                            .setUsrNam(personInfo.getString("personName"))
                            .setContractor(orgMap.getOrDefault(personInfo.getString("orgIndexCode"), "未知"))
                            .setOpTyp(1));
                }
                if (ObjectUtils.isNotEmpty(list)) {
                    SyncMjPersonDataByHk(pageNo + 1, newPersons, orgMap);
                }

            } else {
                XxlJobHelper.log("同步海康门禁人员信息失败");
            }
        }

    }


    private void bulidMjPersonInfo(List<HkPerson> allResult, List<HkPerson> newPersons) {

        Map<String, HkPerson> oldPersonMap = allResult.stream().collect(Collectors.toMap(HkPerson::getUsrIdCard, point -> point, (a, b) -> b));
        if (ObjectUtils.isEmpty(oldPersonMap)) {
            personService.saveBatch(newPersons);
        } else {
            List<HkPerson> addHkPersonList = new ArrayList<>();
            List<HkPerson> updatePersonList = new ArrayList<>();
            List<String> ids = new ArrayList<>();
            newPersons.forEach(person -> {
                ids.add(person.getUsrIdCard());
                HkPerson oldPerson = oldPersonMap.get(person.getUsrIdCard());
                if (ObjectUtils.isEmpty(oldPersonMap.get(person.getUsrIdCard()))) {
                    addHkPersonList.add(person);
                } else {
                    updatePersonList.add(person.setOpTyp(oldPerson.getOpTyp() == 4 ? 2 : oldPerson.getOpTyp()));
                }
            });
            List<HkPerson> deletePersonList = allResult.stream().filter(person -> (!ids.contains(person.getUsrIdCard())) && person.getOpTyp() == 4).toList();
            deletePersonList.forEach(nreg -> nreg.setOpTyp(3));
            XxlJobHelper.log("新增海康人员信息：{}条", addHkPersonList.size());
            personService.saveBatch(addHkPersonList);
            XxlJobHelper.log("修改海康人员信息：{}条", updatePersonList.size());
            personService.updateBatchById(updatePersonList);
            XxlJobHelper.log("删除海康人员信息：{}条", deletePersonList.size());
            personService.updateBatchById(deletePersonList);
        }


    }

}
